<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../res/layui/css/layui.css">

</head>
<body>
<div class="layui-fluid">
    <fieldset class="layui-elem-field layui-field-title">
        <legend>歌单创建</legend>
        <div class="layui-field-box">
            <div class="layui-col-md6">
                <form class="layui-form layui-form-pane" lay-filter="formMusic" id="formMusic">
                    <div class="layui-form-item">
                        <img class="layui-upload-img" id="ID-upload-demo-img"
                             style="width:92px;height: 92px;border: 1px solid rgba(0,0,0,0.1)">
                    </div>
                    <!--表单控件项：文件上传（歌曲文件）-->
                    <div class="layui-form-item">
                        <button class="layui-btn layui-btn-normal" type="button" id="btnMusic">
                            <i class="layui-icon layui-icon-upload"></i>
                            选择封面图
                        </button>
                    </div>
                    <!--表单控件项：歌曲名-->
                    <div class="layui-form-item">
                        <label class="layui-form-label">歌单名:</label>
                        <div class="layui-input-block">
                            <input class="layui-input" type="text" name="name" id="musicname" lay-verify="required"
                                   lay-verType="tips" lay-reqText="请输入歌曲名称">
                        </div>
                    </div>
                    <!--表单控件项：标签-->
                    <div class="layui-form-item">
                        <label class="layui-form-label">标签:</label>
                        <div class="layui-input-block">
                            <input class="layui-input" type="text" name="tags" id="tags"
                                   placeholder="多个标签之间使用逗号(,)分隔" lay-verify="required" lay-verType="tips"
                                   lay-reqText="请输入至少一个标签">
                        </div>
                    </div>
                    <!-- 提交按钮    -->
                    <div class="layui-form-item" style="text-align: right">
                        <button type="button" class="layui-btn layui-btn-warm" lay-submit id="addMusic">确认添加
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </fieldset>
</div>
<script src="../res/layui/layui.js"></script>
<script>
    layui.use(function () {
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;
        //获取文件上传组件
        var upload = layui.upload;
        
        // 从URL参数中获取歌单ID，如果存在则为编辑模式
        var urlParams = new URLSearchParams(window.location.search);
        var musicListId = urlParams.get('id');
        
        // 如果是编辑模式，加载歌单数据
        if (musicListId) {
            $('.layui-field-title legend').text('歌单编辑');
            $('#addMusic').text('确认修改');
            
            $.ajax({
                type: 'get',
                url: '/musicList/details',
                data: {id: musicListId},
                success: function(resp) {
                    if (resp.success && resp.data) {
                        var musicList = resp.data;
                        // 填充表单数据
                        $('input[name="name"]').val(musicList.name);
                        $('#tags').val(musicList.tags || '');
                        if (musicList.pic) {
                            $('#ID-upload-demo-img').attr('src', musicList.pic);
                        }
                        
                        // 重新渲染表单
                        form.render();
                    } else {
                        layer.msg(resp.message || '获取歌单信息失败', {icon: 5});
                    }
                },
                error: function() {
                    layer.msg('网络错误，请稍后重试', {icon: 5});
                }
            });
        }
        
        // 配置文件上传
        var uploadInst = upload.render({
            elem: '#btnMusic',
            url: '/upload', // 上传接口地址，需要根据实际项目调整
            method: 'post',
            field: 'file',
            accept: 'images',
            acceptMime: 'image/*',
            exts: 'jpg|jpeg|png|gif',
            before: function(obj) {
                // 预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result) {
                    $('#ID-upload-demo-img').attr('src', result);
                });
                layer.load(2);
            },
            done: function(res) {
                layer.closeAll('loading');
                if (res.success && res.data) {
                    layer.msg('上传成功', {icon: 6});
                    // 保存上传后的图片路径到隐藏字段
                    $('#ID-upload-demo-img').attr('data-path', res.data);
                } else {
                    layer.msg(res.message || '上传失败', {icon: 5});
                }
            },
            error: function() {
                layer.closeAll('loading');
                layer.msg('上传失败，请稍后重试', {icon: 5});
            }
        });
        
        // 表单提交
        $('#addMusic').on('click', function() {
            // 表单验证
            var name = $('input[name="name"]').val().trim();
            if (!name) {
                layer.msg('请输入歌单名称', {icon: 5});
                return;
            }
            
            // 构建请求数据
            var musicListData = {
                name: name,
                tags: $('#tags').val().trim(),
                pic: $('#ID-upload-demo-img').attr('data-path') || $('#ID-upload-demo-img').attr('src'),
                status: 1 // 默认上架
            };
            
            // 如果是编辑模式，添加id
            if (musicListId) {
                musicListData.id = parseInt(musicListId);
            }
            
            // 发送请求
            var url = musicListId ? '/musicList/update' : '/musicList/add';
            $.ajax({
                type: 'post',
                url: url,
                contentType: 'application/json',
                data: JSON.stringify(musicListData),
                success: function(resp) {
                    if (resp.success) {
                        layer.msg(musicListId ? '修改成功' : '添加成功', {icon: 6});
                        // 延迟后返回列表页面
                        setTimeout(function() {
                            if (window.parent === window) {
                                window.location.href = 'musiclist-list.html';
                            } else {
                                // 如果是在iframe中打开的，关闭弹窗
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            }
                        }, 1500);
                    } else {
                        layer.msg(resp.message || (musicListId ? '修改失败' : '添加失败'), {icon: 5});
                    }
                },
                error: function() {
                    layer.msg('网络错误，请稍后重试', {icon: 5});
                }
            });
        });
    })
</script>
</body>
</html>